/* NOTICE
    OpenJaWS - Open Java Weather Station
    
    Copyright (C) 2008 Grant Gardner <grant@lastweekend.com.au>
    
    OpenJaWS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
NOTICE */

package au.com.lastweekend.openjaws;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.lastweekend.openjaws.api.Readings;
import au.com.lastweekend.openjaws.api.WeatherPlugin;
import au.com.lastweekend.openjaws.api.WeatherPluginException;
import au.com.lastweekend.openjaws.util.LoopRunnable;

/**
 * Main loop that processes readings from the station and passes them to the plugins
 * 
 * @author grant@lastweekend.com.au
 * @version $Id$
 */
public class WeatherLoop extends LoopRunnable {

    private static final Logger LOG = LoggerFactory.getLogger(WeatherLoop.class);

    private WeatherPlugin plugin;

    private Readings readings;;

    public WeatherLoop(WeatherPlugin plugin) {

        this.plugin = plugin;

    }

    @Override
    protected void preLoop() {

        readings = new Readings();
        readings.setReadingTime(null);
    }

    @Override
    protected void inLoop() {

        synchronized (this) {
            try {
                plugin.process(readings);
            } catch (WeatherPluginException e) {
                LOG.error("Exception in WeatherLoop", e);
            }
        }

        try {
            int delay = delay();
            LOG.info("Sleeping for " + delay + "ms");
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            LOG.debug("Interrupted while sleeping", e);
        }
    }

    private int delay() {

        return readings.getSecondsToNextReading() * 1000;
    }

    @PostConstruct
    public void start() {

        super.start("WeatherLoop");
        LOG.info("Started");
    }

    @PreDestroy
    public void destroy() {

        stop();
    }

    @Override
    protected void stopped() {

        LOG.info("Stopped");
    }

    /**
     * For testing only
     * 
     * @return the internal readings instance
     */
    Readings getReadings() {

        return readings;
    }

}
